<?php

namespace app\admin\controller\insurance;

use app\admin\model\InsurancePolicy;
use app\admin\model\InsuranceReport;
use app\admin\model\InsuranceSection;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\response\Json;
use app\admin\service\tool\CommonTool;
use think\db\exception\PDOException;
use think\facade\Db;
use app\admin\service\insurance\PolicyService;

#[ControllerAnnotation(title: '费用报表')]
class Report extends AdminController
{
    protected array $sort = [
        'id'   => 'desc',
    ];

    protected array $allowModifyFields = [
        'amount',
        'scharge',
    ];
    protected $service;

    public function __construct(App $app, PolicyService $service)
    {
        parent::__construct($app);
        self::$model = InsurancePolicy::class;
        $this->service = $service;
    }
    

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = self::$model::where($where)->count() ?: 0;
            list($count, $list) = $this->service->getPageList($where, $page, $limit, $this->sort);
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function report(Request $request) {
        if (env('EASYADMIN.IS_DEMO', false)) {
            $this->error('演示环境下不允许操作');
        }

        list($page, $limit, $where) = $this->buildTableParams();

        $header    = [
            ['保险类型', 'type_txt'],
            ['代理人', 'agent'],
            ['投保人', 'insurer'],
            ['车牌号', 'carno'],
            ['险种', 'section'],
            ['出单日期', 'create_at'],
            ['保费', 'cost'],
            ['代理费ME', 'amount_me'],
            ['代理点ME', 'red_point_me'],
            ['代理费', 'amount'],
            ['代理点', 'red_point'],
            ['手续费', 'scharge'],
            ['未结费用', 'cost_total_un'],
            ['已结费用', 'scharge_total'],
        ];
        $list = self::$model::where($where)
            ->with(['user' => function ($query) {
                $query->field(['id', 'insurer', 'carno'])->find();
            }])
            ->with(['report' => function ($query) {
                $query->find();
            }])
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $res = [];
        $cost_total_un_all = 0;
        $scharge_total_all = 0;
        foreach ($list as $k => &$v) {
            if ($v['type'] == 0) {
                $v['type_txt'] = '交';
            } else if ($v['type'] == 1) {
                $v['type_txt'] = '商';
            } else {
                $v['type_txt'] = '架';
            }
            $list[$k]['insurer'] = $v['user']['insurer'];
            $list[$k]['carno'] = $v['user']['carno'];
            $list[$k]['amount_me'] = $v['report']['amount_me'];
            $list[$k]['red_point_me'] = $v['report']['red_point_me'];
            $list[$k]['amount'] = $v['report']['amount'];
            $list[$k]['red_point'] = $v['report']['red_point'];
            $list[$k]['scharge'] = $v['report']['scharge'];
            $list[$k]['cost_total_un'] = $v['report']['amount'] - $v['report']['scharge'];
            $list[$k]['scharge_total'] = $v['report']['scharge'];
            $cost_total_un_all += $v['report']['amount'] - $v['report']['scharge'];
            $scharge_total_all += $v['report']['scharge'];

            $v['types'] = self::$model::where('batch_ident', $v['batch_ident'])->field('type, id')->select() ?: [];
            $section = $this->service->getSection($v, ['id', 'title']);
            $list[$k]['section'] = $section['title'] ?? '';
        }
        $list[] = ['cost_total_un' => '合计：'.$cost_total_un_all, 'scharge_total' => '合计：'.$scharge_total_all];
        // return json([$header, $list]);
        
        try {
            exportExcel($header, $list);
        }catch (\Throwable $exception) {
            exit('导出失败: ' . $exception->getMessage() . PHP_EOL . $exception->getFile() . PHP_EOL . $exception->getLine());
            $this->error('导出失败: ' . $exception->getMessage() . PHP_EOL . $exception->getFile() . PHP_EOL . $exception->getLine());
        }
    }

    #[NodeAnnotation(title: '属性修改', auth: true)]
    public function modify(Request $request): void
    {
        $this->checkPostRequest();
        $post = $request->post();
        $rule = [
            'id|ID'      => 'require',
            'field|字段' => 'require',
            'value|值'   => 'require',
        ];
        $this->validate($post, $rule);
        $row = self::$model::find($post['id']);

        $flag = $post['field'] != 'cost' 
                && $post['field'] != 'scharge' 
                && $post['field'] != 'amount';
        if ($flag) {
            if ($post['field'] != 'cost'){
                $row = InsuranceReport::where('policy_id', $row['id'])->find();
            }
        }

        if (!$row) {
            $this->error($flag ? '还没有匹配费用' : '数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            Db::transaction(function() use ($post, $row) {
                $row->save([
                    $post['field'] => $post['value'],
                ]);
            });
        }catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
}
